package interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 这是我最开始写的，还用了flag这个变量，其实没有必要
 *
 */
public class AlternatePrint1 {

    public static ReentrantLock lock = new ReentrantLock();
    public static Condition printA = lock.newCondition();
    public static Condition printB = lock.newCondition();
    public static Boolean flag = true;



    public static void printA(){
        lock.lock();
        try {
            if(!flag){
                printA.await();
            }
            Thread.sleep(1000l);
            System.out.println("thread-name:" + Thread.currentThread().getName()+"==output:A");
            printB.signal();
            flag = false;


        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void printB(){
        lock.lock();
        try {
            if(flag){
                printB.await(); //这里之前用printB.wait() 方法导致一直执行不成功 记录采坑点
            }
            Thread.sleep(1000l);
            System.out.println("thread-name:" + Thread.currentThread().getName()+"==output:B");
            printA.signal();
            flag = true;


        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    //线程A
    static class PrintAThread extends Thread {

        @Override
        public void run() {
            while (true){
                printA();
            }
        }
    }

    //线程B
    static class PrintBThread extends Thread {

        @Override
        public void run() {
            while (true){
                printB();
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new AlternatePrint.PrintAThread();
        Thread t2 = new AlternatePrint.PrintBThread();
        t1.start();
        Thread.sleep(1000L);//想让A线程执行，所以休眠1秒钟
        t2.start();
    }
}
